package com.datam.filter;

import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.FilterConfig;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.annotation.WebFilter;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.http.HttpHeaders;
import org.springframework.util.LinkedMultiValueMap;
import org.springframework.util.MultiValueMap;

import com.alibaba.fastjson.JSON;
import com.dm.controller.SysUserController;
import com.dm.dao.SysUserDAO;
import com.dm.entity.SysUserDO;
import com.dm.query.QuerySysUser;
import com.dm.service.SysUserService;
import com.dm.service.impl.SysUserServiceImpl;
import com.dm.utils.HttpClient;


public class SessionFilter  implements Filter{
	
	@Value("${log.info:0}")
    private String info;
	
	//@Value("${openurl}")
    private String url = "http://47.110.54.212:5001/";
	
	 //标示符：表示当前用户未登录(可根据自己项目需要改为json样式)
    String NO_LOGIN = "{\"code\":\"300\"}";

    //不需要登录就可以访问的路径(比如:注册登录等)
    public static String[] includeUrls = new String[]{"/user/login","register","/user/notify","/user/getuserbycode"};

	@Override
	public void destroy() {
		// TODO 自动生成的方法存根
		
	}

	@Override
	public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse,
			FilterChain filterChain) throws IOException, ServletException {
		 HttpServletRequest request = (HttpServletRequest) servletRequest;
	     HttpServletResponse response = (HttpServletResponse) servletResponse;
	     HttpSession session = request.getSession(false);
	     String uri = request.getRequestURI();
	     
	     response.setHeader("Access-Control-Allow-Origin", "*");
	     response.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE,PUT");
	     response.setHeader("Access-Control-Max-Age", "3600");
	     response.setHeader("Access-Control-Allow-Headers", "x-requested-with");
	     response.setHeader("Access-Control-Allow-Credentials","true"); //是否支持cookie跨域
	     response.setHeader("Access-Control-Allow-Origin", request.getHeader("Origin"));
	     System.out.println("filter url:"+uri);
	     //String openId = (String) session.getAttribute("openId");
	     //是否需要过滤
	     boolean needFilter = isNeedFilter(uri);
	     System.out.println(uri+ !needFilter);
	     if (!needFilter) { //不需要过滤直接传给下一个过滤器
	            filterChain.doFilter(servletRequest, servletResponse);
	        } else { //需要过滤器
	            // session中包含user对象,则是登录状态
	          if((session!=null&&session.getAttribute("user") != null)){
	                if("1".equals(info)){
	                	 ServletRequest requestWrapper = null;
	                     if(servletRequest instanceof HttpServletRequest) {
	                         requestWrapper = new RequestWrapper((HttpServletRequest) servletRequest);
	                     }
	                     if(requestWrapper == null) {
	                         filterChain.doFilter(servletRequest, servletResponse);
	                     } else {
	                         filterChain.doFilter(requestWrapper, servletResponse);
	                     }
	                }
	                filterChain.doFilter(request, response);
	            }else{
	            	//是否是微信过来的
//	    			String code = request.getParameter("code");
//					System.out.println("code"+code);
//	    			if(code !=null){
//	    				//获取openId
//	    				String openId = "";
//	    				try {
//	    					System.out.println(url+"userinfo?usercode="+code);
//		    				openId =HttpClient.sendGetRequest(url+"userinfo?usercode="+code, null,new  HttpHeaders());
//						} catch (Exception e) {
//							System.out.println("获取openid 出错");
//							e.printStackTrace();
//							return;
//						}
//	    				System.out.println("openId"+openId);
//	    				//查询数据库
//	    				QuerySysUser querySysUser = new QuerySysUser();
//	    				querySysUser.setWxid(openId);
//	    				System.out.println("sysUserDAO:"+ SysUserServiceImpl.sysUserDAO );
//	    				List<SysUserDO> list =  SysUserServiceImpl.sysUserDAO.selectSysUserList( querySysUser );
//	    				if(list != null && list.size() > 0){
//	    					SysUserDO sysUserDO = list.get(0);
//	    					session.setAttribute("openId", openId);
//	    					session.setAttribute("user", sysUserDO);
//	    	                filterChain.doFilter(request, response);
//	    				}else{
//		    				System.out.println("No seesion");
//		                    response.getWriter().write("404");
//	    				}
//	    			}else{
	    				System.out.println("No seesion");
		                String requestType = request.getHeader("X-Requested-With");
		                //判断是否是ajax请求
		                if(requestType!=null && "XMLHttpRequest".equals(requestType)){
		                    response.getWriter().write("404");
		                }else{
		                    response.getWriter().write("404");
		                }
		                return;
	    			}
//	            }
	        }
	}

	
	/**
     * @Author: xxxxx
     * @Description: 是否需要过滤
     * @Date: 2018-03-12 13:20:54
     * @param uri
     */
	public static void main(String[] args) {
//		System.out.println(isNeedFilter("/data/user/getuserbycode"));
//		System.out.println("/data/user/getuserbycode".contains("/user/getUserByCode"));
//		String openId =HttpClient.sendGetRequest("http://150.109.148.212/"+"userinfo?usercode=081glHpl0YT3qo1rTvnl0P6Ipl0glHpL", null,new  HttpHeaders());
//		System.out.println(openId);
//				System.out.println(openId);
		MultiValueMap<String,String> params = new LinkedMultiValueMap<>();
		List<String> str = new ArrayList<String>();
		Map pushData = new HashMap<>();
		Map info = new HashMap<>();
		info.put("company","test");
		info.put("ass", "test");
		info.put("time", new SimpleDateFormat("yyyy-MM-dd HH").format(new Date()));
		pushData.put("openId","owvIZs9IRPjhGA8eDYrqMHf5i8oA");
		pushData.put("info", info);
		str.add(JSON.toJSONString(pushData));
		params.add("data", "["+String.join(",", str)+"]");
		HttpClient.sendPostRequest("http://150.109.148.212/"+"notify", params);

	}
	class test{
		String openId;
		String info ; 
		public test(String id ,String info){
			this.openId = id ;
			this.info = info ;
					
		}
		public String getOpenId() {
			return openId;
		}
		public void setOpenId(String openId) {
			this.openId = openId;
		}
		public String getInfo() {
			return info;
		}
		public void setInfo(String info) {
			this.info = info;
		}
		
	}
    public static  boolean isNeedFilter(String uri) {
    	boolean bol = true ; 
        for (String includeUrl : includeUrls) {
        	System.out.println(includeUrl+uri.contains(includeUrl));
            if(uri.contains(includeUrl)) {
            	return false;
            }
        }
        return bol;
    }
    
    
	@Override
	public void init(FilterConfig arg0) throws ServletException {
		// TODO 自动生成的方法存根
		
	}

}
